package com.xzhuang.task.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.quartz.impl.triggers.CronTriggerImpl;

import com.xzhuang.task.quartz.ScheduleTask;

public class QuartzUtil {
	public final static String USERINFO = "user";
	public final static String defaultGroupName = "DEFAULT";
	
	private static Map<String,String> maps = new HashMap<String,String>();
	static {

		/*
		 * None：Trigger已经完成，且不会在执行，或者找不到该触发器，或者Trigger已经被删除 NORMAL:正常状态
		 * PAUSED：暂停状态 COMPLETE：触发器完成，但是任务可能还正在执行中 BLOCKED：线程阻塞状态 ERROR：出现错误
		 */
		maps.put("None", "已完成");
		maps.put("NORMAL", "正常等待");
		maps.put("PAUSED", "暂停");
		maps.put("COMPLETE", "执行中");
		maps.put("BLOCKED", "阻塞中");
		maps.put("ERROR", "错误");

	}

	public static String getTrigerStateName(String state) {
		return maps.get(state).toString();
	}

	/**
	 * 判断cron时间表达式正确性
	 * 
	 * @param cronExpression
	 * @return
	 */
	public static boolean isValidExpression(final String cronExpression) {
		CronTriggerImpl trigger = new CronTriggerImpl();
		try {
			trigger.setCronExpression(cronExpression);
			Date date = trigger.computeFirstFireTime(null);
			return date != null && date.after(new Date());
		} catch (ParseException e) {
		}
		return false;
	}

	public static String[] getExtendParam(String paramary) {
		String[] ret = new String[2];
		
		if (paramary == null){
			ret[0] = "1";
			ret[1] = "";
			System.out.println(paramary  + "---AA---" + ret[0] + "====" + ret[1]);
			return ret;
		}
		if (paramary.indexOf("|") != -1) {
			ret = paramary.split("\\|");
			System.out.println(paramary  + "---BB---" + ret[0] + "====" + ret[1]);
			return ret; 
		} else {
			ret[0] = paramary;
			ret[1] = "";
			System.out.println(paramary  + "---cc---" + ret[0] + "====" + ret[1]);
			return ret;
		}

	}

	public static void main(String args[]) throws Exception {
		// System.out.println(isValidExpression("fadfadfad"));
		// URI u = new URI("fasdfasdfasd");
		// System.out.println(isValidExpression("0 0/1 * * * ?"));
		// System.out.println(isURL("http://aa.localhost/dd/fad"));

		//System.out.println(isURL("http://locahost:87/fadsf/p?a=00&b=dd"));
		//System.out.println(isURL("fasdfasdfasd"));
		//System.out.println(isURL("http://fddfdfd"));
		//System.out.println(isURL("www.baidu.com:8080/fasdfad/fdd?ad=ff"));
		
		
		String test = "1|测试乱码";
		System.out.println(test.indexOf("|") + "<<<---------->>>" + test.indexOf("\\|"));
		String[] tp = test.split("\\|");
		System.out.println(tp[0] + "-----------" + tp[1]);

	}

	public static boolean isNotBlank(Object obj) {
		return obj == null ? false : true;
	}

	public static String getFormatDateString(Date date) {
		if (date == null)
			return "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleTask
	 */
	public static void invokMethod(ScheduleTask scheduleTask) {
		Object object = null;
		Class clazz = null;
		// springId不为空先按springId查找bean
		if (StringUtils.isNotBlank(scheduleTask.getSpringId())) {
			object = SpringContextUtil.getBean(scheduleTask.getSpringId());
		} else if (StringUtils.isNotBlank(scheduleTask.getBeanClass())) {
			try {
				clazz = Class.forName(scheduleTask.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		if (object == null) {
		
			return;
		}
		clazz = object.getClass();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(scheduleTask.getMethodName());
		} catch (NoSuchMethodException e) {
			// log.error("任务名称 = [" + scheduleJob.getJobName() +
			// "]---------------未启动成功，方法名设置错误！！！");
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (method != null) {
			try {
				method.invoke(object);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static boolean isURL(String pInput) {
		if (pInput == null) {
			return false;
		}
		Pattern p = Pattern.compile("^(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$", Pattern.CASE_INSENSITIVE);
		// Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(pInput);
		return matcher.matches();
	}

	public static boolean checkURL(String url) {
		Pattern p = Pattern.compile("^(http|www|ftp|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$", Pattern.CASE_INSENSITIVE);
		return p.matcher(url).matches();
	}

	public static String getConfigValue(String pathFileName) throws Exception {

		String lineTxt = "";
		try {

			File file = new File(pathFileName);
			if (file.isFile() && file.exists()) {
				Scanner in = new Scanner(file);

				while (in.hasNextLine()) {
					String str = in.nextLine();
					if (str != null && str.length() > 0)
						lineTxt += str;
					// String str = in.nextLine();
					// System.out.println(str);
				}
			} else {
				throw new Exception("找不到指定的密码文件  :" + pathFileName);
			}
			/*
			 * String encoding = "GBK"; File file = new File(pathFileName); if
			 * (file.isFile() && file.exists()) { InputStreamReader read = new
			 * InputStreamReader(new FileInputStream(file), encoding);
			 * BufferedReader bufferedReader = new BufferedReader(read); while
			 * ((lineTxt = bufferedReader.readLine()) != null) {
			 * System.out.println(lineTxt); } read.close(); } else { throw new
			 * Exception("找不到指定的密码文件  :" + pathFileName); }
			 */

			return lineTxt;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
			/*
			 * System.out.println(e.getMessage()); throw new
			 * Exception("读取密码文件内容出错");
			 */
		}
		//return null;
	}
	
	
	public static boolean isJsonFormat(String json){
		boolean is = false;
		if(null == json || json.length() == 0){
			return false;
		}
		try{
			JSONObject jsonObject = JSONObject.fromObject(json); 
			return true;
		}catch(Exception e){
			return false;
		}
		//return is;
	}

}
